//
//  @ Project : Galaxy Star Trading System
//  @ File Name : ScopeGuard.h
//  @ Date : 2014/9/5
//  @ Author :
//
//


#if !defined(SCOPEGUARD_H)
#define SCOPEGUARD_H

#include <functional>

namespace GSTrader
{
	namespace Util
	{
		class CScopeGuard
		{
		public:
			explicit CScopeGuard(std::function<void()> onExitScope)
				: onExitScope_(onExitScope), dismissed_(false)
			{ }

			~CScopeGuard()
			{
				if (!dismissed_)
				{
					onExitScope_();
				}
			}

			void Dismiss()
			{
				dismissed_ = true;
			}

		private:
			std::function<void()> onExitScope_;
			bool dismissed_;

		private: // noncopyable
			CScopeGuard(CScopeGuard const&) {};
			CScopeGuard& operator = (CScopeGuard const&) {};
		};

	}
}

#define SCOPEGUARD_LINENAME_CAT(name, line) name##line
#define SCOPEGUARD_LINENAME(name, line) SCOPEGUARD_LINENAME_CAT(name, line)

#define ON_SCOPE_EXIT(callback) GSTrader::Util::CScopeGuard SCOPEGUARD_LINENAME(EXIT, __LINE__)(callback)

/*
ON_SCOPE_EXIT([&]{
rsp_thread.join();
mon_thread.join();
zmonitor_destroy(&mon);
zsocket_destroy(ctx, dealer);
zctx_destroy(&ctx);
});

*/

#endif // SCOPEGUARD_H